package com.bwie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import com.bwie.vo.LoginForm;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
* @author 陈彤彤
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2025-04-24 08:16:31
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public R adminLogin(LoginForm loginForm) {
        //获取用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getUsername,loginForm.getUsername()));
        //判断用户是否重复
        if (user == null){
            return R.ERROR(404,"用户名重复");
        }
        //判断密码是否正确
        if (!user.getPassword().equals(loginForm.getPassword())){
            return R.ERROR(500,"密码错误");
        }

        //生成token
        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "123456")
                .claim("id", user.getId())
                .claim("username", user.getUsername())
                .claim("nickName", user.getNickName())
                .compact();

        //存入缓存，设置存活时长
        String redisToken = "token-" + user.getId();
        redisTemplate.opsForValue().set(redisToken,token,15, TimeUnit.MINUTES);

        //返回token
        user.setToken(token);
        //将密码设置空
        user.setPassword(null);
        return R.OK(user);
    }

    @Override
    public R userList(PageInfoVo pageInfoVo) {
        Page<User> userPage = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByDesc(User::getId);

        if (StringUtils.isNoneEmpty(pageInfoVo.getKeyWord())){
            wrapper.lambda().like(User::getUsername,pageInfoVo.getKeyWord());
        }

        Page<User> page = userMapper.selectPage(userPage,wrapper);

        return R.OK(page);
    }

}




